<?php
class TbfString{
    static function TrimPrefix($s,$prefix){
        if (strpos($s,$prefix)!==0){
            return false;
        }
        return substr($s,strlen($prefix));
    }

    /**
     * Contains returns true if substr is within s.
     * @param string $s 长字符串
     * @param string $substr 短字符串
     * @return bool
     */
    static function Contains($s,$substr){
        return strpos($s,$substr)!==false;
    }

    static function HasPrefix($s,$prefix){
        return strpos($s,$prefix)===0;
    }

    static function ToStringOrEmpty($s){
        if (!is_string($s)){
            return '';
        }
        return $s;
    }

    static function SplitUtf8($s){
        return preg_split('//u',$s, -1, PREG_SPLIT_NO_EMPTY);
    }
    static function Utf8ToIntArray($str){
        $unicode = array();
        $values = array();
        $lookingFor = 1;
        for ($i = 0; $i < strlen( $str ); $i++ ) {
            $thisValue = ord( $str[ $i ] );
            if ( $thisValue < 128 ) {
                $unicode[] = $thisValue;
            }
            else {
                if ( count( $values ) == 0 ) $lookingFor = ( $thisValue < 224 ) ? 2 : 3;
                $values[] = $thisValue;
                if ( count( $values ) == $lookingFor ) {
                    $number = ( $lookingFor == 3 ) ?
                        ( ( $values[0] % 16 ) * 4096 ) + ( ( $values[1] % 64 ) * 64 ) + ( $values[2] % 64 ):
                        ( ( $values[0] % 32 ) * 64 ) + ( $values[1] % 64 );
                    $unicode[] = $number;
                    $values = array();
                    $lookingFor = 1;
                } // if
            } // if
        } // for
        return $unicode;
    }
    const ErrCodePoint = 0xFFFD;
    //返回utf8的第一个code的值
    static function Utf8FirstCode($str){
        if (strlen($str)<1){
            return ErrCodePoint;
        }
        $v0 = ord($str[0]);
        if ($v0<128){
            return $v0;
        }
        if (strlen($str)<2){
            return ErrCodePoint;
        }
        $v1 = ord($str[1]);
        if ($v0<224){
            return (( $v0 % 32 ) * 64) + ( $v1 % 64 );
        }
        if (strlen($str)<3){
            return ErrCodePoint;
        }
        $v2 = ord($str[2]);
        if ($v0<240){
            return (( $v0 % 16 ) * 4096 ) + ( ( $v1 % 64 ) * 64 ) + ( $v2 % 64 );
        }
        throw new \Exception('point code too high >65535 (not implement)');
    }
    //去掉头尾的空格
    static function Utf8TrimSpace($s){
        return preg_replace('/^[\pZ\pC]+|[\pZ\pC]+$/u','',$s);
    }
    //去掉所有空格,英文会悲剧
    static function Utf8RemoveSpace($s){
        return preg_replace('/[\pZ\pC]+/u','',$s);
    }
}